package org.bing.engine.statistic.helper;

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;

public class JvmStatHelper {
    private static final Runtime runtime = Runtime.getRuntime();
    private static final ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
    private static long lastThreadTimes = -1;
    private static long lastThreadFlag = -1;

    public synchronized static float getCpuUsage() {
        long times = 0;
        long[] ids = threadMXBean.getAllThreadIds();
        for (int i = 0, len = ids.length; i < len; i++) {
            times += threadMXBean.getThreadCpuTime(ids[i]);
        }
        // ready to calc
        float usage = 0;
        long now = System.currentTimeMillis();
        if (lastThreadFlag >= 0) {
            usage = ((float) (times - lastThreadTimes)) / (10000 * (now - lastThreadFlag));
            usage = (float) (Math.round(usage * 100)) / 100;
        }
        // reset last value
        lastThreadFlag = now;
        lastThreadTimes = times;

        return usage;
    }

    public static float getMemoryUsage() {
        long free = runtime.freeMemory();
        long max = runtime.maxMemory();
        long total = runtime.totalMemory();
        float usage = ((float) (total - free) * 100) / max;
        usage = (float) (Math.round(usage * 100)) / 100;
        return usage;
    }

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 10; i++) {
            System.out.println(JvmStatHelper.getMemoryUsage());
            Thread.sleep(500);
            System.gc();
            for (long j = 0; j < 1000000000; j++) {
                j++;
            }
            System.out.println(JvmStatHelper.getCpuUsage());
        }
    }
}
